//
//  BK_SP_Success_VC.m
//  bestkeep
//
//  Created by TOPTEAM on 2017/3/31.
//  Copyright © 2017年 utouu. All rights reserved.
//

#import "BK_SP_Success_VC.h"
#import "BK_OD_Color.h"
#import "BKUserStatusInfo.h"

#import "BK_SPS_Status_Cell.h"
#import "BK_SPS_Address_Cell.h"
#import "BK_SPS_Detail_Cell.h"
#import "BK_SPS_List_Cell.h"
#import "BK_SPS_Member_Cell.h"


#import "BKMyCommon.h"
#import "BKUserRequestUrl.h"
#import "UTLogin.h"
#import "BKMyAction.h"
#import "BKUserMyCouponController.h"
#import "Mediator+BKMy.h"
#import "BK_OD_Tool.h"

#import "UIViewController+BackButtonHandler.h"
#import <Masonry.h>

#import "BK_SP_OD_Model.h"

@interface BK_SP_Success_VC ()
<
UITableViewDelegate,
UITableViewDataSource,
BK_SPS_Member_Delegate
>
@property(nonatomic, strong)UITableView *tableView;
@property(nonatomic, strong)ExceptionView *exceptionView;
@property(nonatomic, strong)NSMutableArray*marr_Section;


@property(nonatomic, strong)BK_SP_OD_Model* model_OD;



//@property(nonatomic, strong) UIView *back_White;

@end

@implementation BK_SP_Success_VC

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self  setProperty];
    [self  createUI];
    [self  check_NetWork];
    
}

#pragma mark==================setProperty======================
-(void)setProperty{
    self.view .backgroundColor = [UIColor whiteColor];
    self.edgesForExtendedLayout = UIRectEdgeNone;
    self.title = @"支付结果";
    if( ([[[UIDevice currentDevice] systemVersion] doubleValue]>=7.0)) {
        self.edgesForExtendedLayout = UIRectEdgeNone;
        self.extendedLayoutIncludesOpaqueBars = NO;
        self.automaticallyAdjustsScrollViewInsets = NO;
        self.modalPresentationCapturesStatusBarAppearance = NO;
        self.navigationController.navigationBar.clipsToBounds = NO;
    }
    _marr_Section=[[NSMutableArray alloc]init];
    
}

#pragma mark==================createUI======================
-(void)createUI{
    
    
    
//    
//    _back_White=[[UIView alloc]init];
//    _back_White.backgroundColor=[UIColor whiteColor];
//    [self.view addSubview:_back_White];
//    
//    
//    
    
    
    
    
    
    
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    _tableView.backgroundColor = RGBACOLOR(242, 242, 242, 1);
    _tableView.showsVerticalScrollIndicator = NO;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLineEtched;
    _tableView.delegate = self;
    _tableView.dataSource = self;
    
    [self.view addSubview:_tableView];
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(self.view);
        make.top.mas_equalTo(self.view).offset(0);
        make.bottom.mas_equalTo(self.view.mas_bottom).offset(0);
    }];
    
}
#pragma mark==================checkNet======================
-(void)check_NetWork{
    RequestReachabilityStatus status = [RequestManager reachabilityStatus];
    switch (status) {
        case RequestReachabilityStatusReachableViaWiFi:
        case RequestReachabilityStatusReachableViaWWAN: {
            /*
             *  获取小店订单详情数据
             */
            [self get_BK_StoreOrderDetail_Data];
//            [self Create_Marr_Section];
        }
            break;
        default: {
            [HUD dismiss];
            
            self.exceptionView = [ExceptionView exceptionViewWithType:ExceptionCodeTypeNoNetwork];
            ExceptionViewAction *action = [ExceptionViewAction actionWithType:ExceptionCodeTypeNoNetwork handler:^(ExceptionViewAction *action) {
                [self.exceptionView dismiss];
                self.exceptionView = nil;
                [self check_NetWork];
            }];
            [self.exceptionView addAction:action];
            [self.exceptionView showInView:self.view];
        }
            break;
    }
}
/*
 * 获取小店订单详情数据
 */
-(void)get_BK_StoreOrderDetail_Data{
    
    
    /*
    接口名称：	getStoreOrder
    接口用途：	获取小店订单详情
    method：	GET
    接口地址：	store/getOrder
    输入参数：
    key	参数类型	是否必须	参数解释
    orderNo	string	是	小店订单号
    返回数据：
    {
        "success": "true/false //成功/失败",
        "msg": "xxx //返回消息",
        "code": "xxx",
        "data":
        {
            "pay_way": "10:账户余额，20：支付宝，30：微信,支付方式",
            "pay_status": "支付状态 0：未支付，1:支付成功，2：支付失败",
            "pay_amount": "xxxx支付金额",
            "order_no": "xxxx订单号",
            "create_time": "下单时间",
            "discount_amount": "xxxx优惠金额",
            "store_address": "xxx小店地址",
        }
    }
    */
    
    NSString *const BKStoreGetOrder_URL      = @"store/getOrder";
    
    
    NSDictionary *paramDic =  @{@"orderNo" : _model.order_no};
    [BKIndicationView showInView:self.view];

    [[RequestManager manager] bkDataRequest:RequestMethodGet URLString:kOrderURL(BKStoreGetOrder_URL) parameters:paramDic success:^(id  _Nullable responseObject){
        [BKIndicationView dismiss];
        BOOL success = [responseObject[@"success"] boolValue];
        
//        [---POST----Result----200--]:{"code":"","data":{"order_no":"20170410112346233229","store_address":"陕西省-西安市碑林区店","pay_amount":45,"pay_way":10,"create_time":"2017-04-10 11:23:45","pay_status":1,"discount_amount":0},"success":true,"msg":""}     --request.URL-->http://api.test.bestkeep.cn/store/getOrder?orderNo=20170410112346233229
        if (!success) {
            
            kOrderPromptMsg(responseObject[@"msg"]);
            //            return;
            
        }else{
            
            if ([responseObject[@"success"] boolValue]) {
                if(responseObject[@"data"]){

                    _model_OD = [BK_SP_OD_Model  mj_objectWithKeyValues:responseObject[@"data"]];
                    
                    [self Create_Marr_Section];
                    
                }else{
                    self.exceptionView = [ExceptionView exceptionViewWithType:ExceptionCodeTypeNoData];
                    ExceptionViewAction *action = [ExceptionViewAction actionWithType:ExceptionCodeTypeNoData handler:^(ExceptionViewAction *action) {
                        [self.exceptionView dismiss];
                        self.exceptionView = nil;
                        [self get_BK_StoreOrderDetail_Data];
                    }];
                    [self.exceptionView addAction:action];
                    [self.exceptionView showInView:self.view];

                }
                
            }else{
                
                /*
                 * 请求失败
                 */
                self.exceptionView = [ExceptionView exceptionViewWithType:ExceptionCodeTypeRequestFailed];
                ExceptionViewAction *action = [ExceptionViewAction actionWithType:ExceptionCodeTypeRequestFailed handler:^(ExceptionViewAction *action) {
                    [self.exceptionView dismiss];
                    self.exceptionView = nil;
                    [self get_BK_StoreOrderDetail_Data];
                }];
                [self.exceptionView addAction:action];
                [self.exceptionView showInView:self.view];
                
            }
            
        }
        
        
    }failure:^(id  _Nullable responseObject, NSError * _Nullable error){
        [BKIndicationView dismiss];
        NSString *errorMsg;
        if (error.code == -1001) {
            errorMsg = @"请求超时";
        }else if(error.code == 502){
            errorMsg = @"服务器开小差了，请稍后再试！";
        }else{
            errorMsg = @"请求失败";
        }
        kOrderPromptMsg(errorMsg);
        
    }];

}


-(void)Create_Marr_Section{
    
    //    NSMutableArray * marr_Cells=[[NSMutableArray alloc]init];
    
    
    CellModel* model0 =[[CellModel alloc]init];
    model0.reuseIdentifier = NSStringFromClass([BK_SPS_Status_Cell class]);
    model0.className=NSStringFromClass([BK_SPS_Status_Cell class]);
    model0.height = [BK_SPS_Status_Cell computeHeight:nil];
    model0.selectionStyle=UITableViewCellSelectionStyleNone;
    model0.accessoryType=UITableViewCellAccessoryNone;
    //    [marr_Cells addObject:model0];
    
    CellModel* model1 =[[CellModel alloc]init];
    model1.reuseIdentifier = NSStringFromClass([BK_SPS_Address_Cell class]);
    model1.className=NSStringFromClass([BK_SPS_Address_Cell class]);
    model1.height = [BK_SPS_Address_Cell computeHeight:nil];
    model1.selectionStyle=UITableViewCellSelectionStyleNone;
    model1.accessoryType=UITableViewCellAccessoryNone;
    //    [marr_Cells addObject:model1];
    
    
    CellModel* model2 =[[CellModel alloc]init];
    model2.reuseIdentifier = NSStringFromClass([BK_SPS_Detail_Cell class]);
    model2.className=NSStringFromClass([BK_SPS_Detail_Cell class]);
    model2.height = [BK_SPS_Detail_Cell computeHeight:nil];
    model2.selectionStyle=UITableViewCellSelectionStyleNone;
    model2.accessoryType=UITableViewCellAccessoryNone;
    //    [marr_Cells addObject:model2];
    
    
    CellModel* model3 =[[CellModel alloc]init];
    model3.reuseIdentifier = NSStringFromClass([BK_SPS_List_Cell class]);
    model3.className=NSStringFromClass([BK_SPS_List_Cell class]);
    model3.height = [BK_SPS_List_Cell computeHeight:nil];
    model3.selectionStyle=UITableViewCellSelectionStyleNone;
    model3.accessoryType=UITableViewCellAccessoryNone;
    //    [marr_Cells addObject:model3];
    
    
    CellModel* model4 =[[CellModel alloc]init];
    model4.reuseIdentifier = NSStringFromClass([BK_SPS_Member_Cell class]);
    model4.className=NSStringFromClass([BK_SPS_Member_Cell class]);
    model4.height = [BK_SPS_Member_Cell computeHeight:nil];
    model4.selectionStyle=UITableViewCellSelectionStyleNone;
    model4.accessoryType=UITableViewCellAccessoryNone;
    
    
    
    
    /*
     * 状态段
     */
    SectionModel *model_Section0=[SectionModel sectionModelWithTitle:@"" cells:@[model0]];
    model_Section0.headerhHeight=10;
    model_Section0.footerHeight=10;
    [_marr_Section addObject:model_Section0];
    
    
    /*
     * 地址段
     */
    SectionModel *model_Section1=[SectionModel sectionModelWithTitle:@"" cells:@[model1]];
    model_Section1.headerhHeight=0.0001;
    model_Section1.footerHeight=1;
    [_marr_Section addObject:model_Section1];
    
    
    /*
     * 详情段
     */
    SectionModel *model_Section2=[SectionModel sectionModelWithTitle:@"" cells:@[model2]];
    model_Section2.headerhHeight=0.0001;
    model_Section2.footerHeight=1;
    [_marr_Section addObject:model_Section2];
    
    /*
     * 列表段
     */
    SectionModel *model_Section3=[SectionModel sectionModelWithTitle:@"" cells:@[model3]];
    model_Section3.headerhHeight=0.0001;
    model_Section3.footerHeight=0.0001;
    [_marr_Section addObject:model_Section3];
    
    BKUserStatusInfo * userStatusInfo =[BKUserStatusInfo currentUser];
    if ([userStatusInfo.vipFlag integerValue]==1) {
        /*
         * 如果是VIP
         */
        
        
    }else{
        /*
         * 不是VIP
         */
        
        /*
         * 开通会员
         */
        SectionModel *model_Section4=[SectionModel sectionModelWithTitle:@"" cells:@[model4]];
        model_Section4.headerhHeight=10;
        model_Section4.footerHeight=0.0001;
        [_marr_Section addObject:model_Section4];
        
    }
    
    
    [_tableView reloadData];
}

#pragma mark tableView 代理相关
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return _marr_Section.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    SectionModel *sm = _marr_Section[section];
    return sm.cells.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    SectionModel *sm = _marr_Section[section];
    
    NSLog(@"sm.headerhHeight-->%f",sm.headerhHeight);
    
    return sm.headerhHeight;
    
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    SectionModel *sm = _marr_Section[section];
    
    NSLog(@"sm.footerHeight-->%f",sm.footerHeight);
    
    return sm.footerHeight;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    return nil;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    return nil;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    SectionModel *sm = _marr_Section[indexPath.section];
    CellModel *cm = sm.cells[indexPath.row];
    
    return cm.height;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    SectionModel *sm = _marr_Section[indexPath.section];
    CellModel *cm = sm.cells[indexPath.row];
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cm.reuseIdentifier];
    if (!cell) {
        cell = [[NSClassFromString(cm.className) alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cm.reuseIdentifier];
    }
    cell.selectionStyle = cm.selectionStyle;
    
    if ([cm.className isEqualToString:NSStringFromClass([BK_SPS_Detail_Cell class])]) {
        BK_SPS_Detail_Cell *ex_cell=(BK_SPS_Detail_Cell *)cell;
        [ex_cell relayOut_UI:_model_OD];
    }

    if ([cm.className isEqualToString:NSStringFromClass([BK_SPS_Member_Cell class])]) {
        BK_SPS_Member_Cell *ex_cell=(BK_SPS_Member_Cell *)cell;

        ex_cell.delegate=self;
    }
    
    if ([cm.className isEqualToString:NSStringFromClass([BK_SPS_Address_Cell class])]) {
        BK_SPS_Address_Cell *ex_cell=(BK_SPS_Address_Cell *)cell;
        [ex_cell relayOutUIWithModel:_model_OD];

    }
    
    if ([cm.className isEqualToString:NSStringFromClass([BK_SPS_List_Cell class])]) {
        BK_SPS_List_Cell *ex_cell=(BK_SPS_List_Cell *)cell;
        [ex_cell relayOutUIWithModel:_model_OD];
        
    }
    
    
    
    return cell;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    
}

#pragma mark--开通会员
-(void)BK_SPS_Member_clicked{
 
    BOOL  isLogin = [BKMyCommon userIsLoginWithInController:self];
    
    if (isLogin) {
        
        NSString *urlStr = [UserPassPortStr stringByAppendingString:AccountLoginUrlStr];
        NSString *tgt = [[Mediator sharedInstance]BKMyUserInfo][BKMyUserGetTGTKey];
        NSString *stUrl = [NSString stringWithFormat:@"%@/%@", urlStr, tgt];
        NSString *value = [UserWebStr stringByAppendingString:@"profile/vip"];
        NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:value,@"service", nil];
        NSDictionary *headDic = [UTLogin getSTHeadDictionary:dic params:dic strurl:stUrl];
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        manager.requestSerializer = [AFHTTPRequestSerializer serializer];
        manager.responseSerializer = [AFHTTPResponseSerializer serializer];
        manager.securityPolicy.allowInvalidCertificates = YES;
        manager.securityPolicy.validatesDomainName = NO;
        for (NSString *key in [headDic allKeys]) {
            NSString *value = [headDic objectForKey:key];
            [manager.requestSerializer setValue:value forHTTPHeaderField:key];
        }
        [BKIndicationView showInView:self.view];
        [manager POST:stUrl parameters:dic progress:^(NSProgress * _Nonnull uploadProgress) {
            
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            [BKIndicationView dismiss];
            NSLog(@"%@", responseObject);
            NSString *st = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
            
            BKUserMyCouponController *coupon = [[BKUserMyCouponController alloc] init];
            coupon.requestUrl = [NSString stringWithFormat:@"%@%@%@",UserWebStr,@"profile/vip?ticket=",st];
            [self.navigationController pushViewController:coupon animated:YES];
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            [BKIndicationView dismiss];
            NSLog(@"Error: %@", error);
            if (error.code==502) {
                [HUD showErrorMessage:@"服务器开小差了，请稍后再试！"];
            }else{
                [HUD showErrorMessage:error.localizedDescription];
            }
        }];
    }
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(BOOL) navigationShouldPopOnBackButton ///在这个方法里写返回按钮的事件处理
{
    [self.navigationController popToRootViewControllerAnimated:YES];
    return YES;
}



/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
